package com.gitee.wsl.compose.ui.textfield.color

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import com.gitee.wsl.compose.ui.base.TextField


@Composable
fun TextField.Color(
    value: Int,
    onValueChanged: (Int) -> Unit,
    label: String,
    suffix: String = "",
    range: IntRange = 0..255,
    parse: (Int) -> String = { it.toString() },
    parseBack: (String) -> Int? = { it.toInt() }
) {
    //TODO TextField clean button
    var colorTextValue by remember {
        mutableStateOf(TextFieldValue(parse(value) + suffix))
    }
    LaunchedEffect(value) {
        colorTextValue = colorTextValue.copy(parse(value) + suffix)
    }
    Row(
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        TextField(
            value = colorTextValue,
            onValueChange = {
                val isNewValue = colorTextValue.text != it.text
                colorTextValue = it
                if (isNewValue) {
                    val newValue = parseBack(it.text.removeSuffix(suffix)) ?: return@TextField
                    val inRange = newValue in range
                    if (newValue != value && inRange) {
                        onValueChanged(newValue)
                    }
                }
            },
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
            modifier = Modifier.width(120.dp).fillMaxWidth()
        )
        Text(label, color = MaterialTheme.colorScheme.secondary)
    }
}